package com.sky.besthardtool.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;

import com.sky.besthardtool.R;
import com.sky.besthardtool.base.ActionBarBaseA;
import com.sky.besthardtool.category.serialport.adapter.CmdAdapter;
import com.sky.besthardtool.category.serialport.api.SerialPortFinder;
import com.sky.besthardtool.utils.SpUtil;


public class SerialConnectA extends ActionBarBaseA implements View.OnClickListener {

    private Spinner sSpinner; //serialport
    private Spinner bSpinner; //baudrate
    private TextView btnConnect;

    private final SerialPortFinder finder = new SerialPortFinder();

    private int bRate = 115200; //波特率
    private String com = "/dev/ttyS3";//串口文件


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect);

        initUI();

        final String[] ss = finder.getAllDevicesPath();
        final String[] bb = getResources().getStringArray(R.array.baudrate);

        CmdAdapter sAdapter = new CmdAdapter(this, ss);
        CmdAdapter bAdapter = new CmdAdapter(this, bb);

        sSpinner.setAdapter(sAdapter);
        bSpinner.setAdapter(bAdapter);


        bSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                bRate = Integer.parseInt(bb[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                com = ss[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void initUI() {
        btnConnect = (TextView) findViewById(R.id.btn_connect);
        sSpinner = (Spinner) findViewById(R.id.s_spinner);
        bSpinner = (Spinner) findViewById(R.id.b_spinner);
        btnConnect.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_connect:
                SpUtil.putBaudrate(SerialConnectA.this, bRate);
                SpUtil.putCom(SerialConnectA.this, com);
                Intent intent = new Intent(SerialConnectA.this, InfoTransferA.class);
                startActivity(intent);
                break;
        }
    }
}
